package com.gylang.common.jwt;

import java.io.*;
import java.nio.file.Files;
import java.security.*;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64;

/**
 * @author gylang,
 * @data 2019/12/7 11:03,
 * @DESC
 */
public class RsaUtils {


    private static final int DEFAULT_KEY_SIZE = 2048;

    /**
     * 根据密文 生成ras公钥私钥 并写入文件
     * @param publicKeyFileName         公钥文件名
     * @param privateKeyFileName        私钥文件名
     * @param secret                     生成秘钥的密文
     * @throws
     */
    public static void generateKey(String publicKeyFileName, String privateKeyFileName, String secret, int keySize) throws Exception {

        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
        SecureRandom secureRandom = new SecureRandom(secret.getBytes());
        keyPairGenerator.initialize(Math.max(keySize, DEFAULT_KEY_SIZE), secureRandom);
        KeyPair keyPair = keyPairGenerator.genKeyPair();
        // 获取公钥并写出
        byte[] publicKeyBites = keyPair.getPublic().getEncoded();
        publicKeyBites = Base64.getEncoder().encode(publicKeyBites);
        writeFile(publicKeyFileName, publicKeyBites);
        //获取私钥并写出
        byte[] privateKeyBytes = keyPair.getPrivate().getEncoded();
        privateKeyBytes = Base64.getEncoder().encode(privateKeyBytes);
        writeFile(privateKeyFileName, privateKeyBytes);
    }

    private static byte[] readFile(String fileName) throws Exception {
        return Files.readAllBytes(new File(fileName).toPath());
    }
    private static void writeFile(String destPath, byte[] content) throws IOException {

        File dest = new File(destPath);
           if (!dest.exists()) {
               dest.createNewFile();
           }
            FileOutputStream fos = new FileOutputStream(dest);
            fos.write(content);
            fos.close();

    }

    /**
     * 获取私钥
     * @param bytes     私钥字节形式
     * @return
     */
    public static PrivateKey getPrivateKey(byte[] bytes) throws NoSuchAlgorithmException, InvalidKeySpecException {
        bytes = Base64.getDecoder().decode(bytes);
        PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(bytes);
        KeyFactory factory = KeyFactory.getInstance("RSA");
        return factory.generatePrivate(spec);
    }
    public static PrivateKey getPrivateKey(String flieName) throws Exception {
       byte[] bytes = readFile(flieName);
        return getPrivateKey(bytes);
    }


    /**
     * 获取公钥
     * @param bytes     公钥字节信息
     * @return
     */
    public static PublicKey getPublicKey(byte[] bytes) throws NoSuchAlgorithmException, InvalidKeySpecException {
        bytes = Base64.getDecoder().decode(bytes);
        X509EncodedKeySpec spec = new X509EncodedKeySpec(bytes);
        KeyFactory factory = KeyFactory.getInstance("RSA");
        return factory.generatePublic(spec);
    }
    public static PublicKey getPublicKey(String flieName) throws Exception {
        byte[] bytes = readFile(flieName);
        return getPublicKey(bytes);
    }
}
